#include <vector>

using namespace std;

class Solution {
public:
    int maxScore(vector<int>& cardPoints, int k) {
        vector<int> left(cardPoints.size() + 1);
        vector<int> right(cardPoints.size() + 1);
        for (int i = 0, cnt = 0; i < cardPoints.size(); i++) {
            cnt += cardPoints[i];
            left[i + 1] = cnt;
        }
        for (int i = cardPoints.size() - 1, cnt = 0; i >= 0; i--) {
            cnt += cardPoints[i];
            right[i] = cnt;
        }
        int ans = 0;
        for (int i = 0; i <= k; i++) {
            ans = max(ans, left[i] + right[cardPoints.size() - (k - i)]);
        }
        return ans;
    }
};